<template>
  <div class="tasks-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">任务管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新建任务
          </el-button>
        </div>
      </template>

      <!-- 筛选 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.title" placeholder="搜索任务" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待办" value="todo" />
            <el-option label="进行中" value="doing" />
            <el-option label="已完成" value="done" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="searchForm.priority" placeholder="选择优先级" clearable>
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 任务列表 -->
      <el-table :data="paginatedTasks" border v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="任务名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="project" label="所属项目" width="150" show-overflow-tooltip />
        <el-table-column prop="assignee" label="负责人" width="100" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :color="getProgressColor(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="截止日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="success" @click="handleComplete(row)">完成</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredTasks.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const loading = ref(false)
const searchForm = reactive({
  title: '',
  status: '',
  priority: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  size: 10
})

// 存储所有任务数据
const allTasks = ref([])

// 生成模拟数据
const generateMockData = () => {
  const taskTitles = [
    '需求文档编写', 'UI设计稿', '数据库设计', '前端页面开发', '后端接口开发',
    '单元测试编写', '集成测试', '性能优化', '代码审查', '部署上线',
    '用户培训', '系统维护', 'Bug修复', '功能迭代', '需求分析',
    '技术方案设计', 'API文档编写', '用户手册编写', '数据迁移', '系统测试',
    '安全测试', '压力测试', '代码重构', '技术调研', '原型设计',
    '交互设计', '视觉设计', '前端组件开发', '后端服务开发', '数据库优化',
    '缓存优化', '接口优化', '页面性能优化', '移动端适配', '浏览器兼容',
    '第三方集成', '支付接口对接', '消息推送', '日志系统', '监控系统',
    '报表开发', '数据分析', '需求评审', '技术评审', '上线验收'
  ]
  
  const projects = [
    'ERP系统开发', '商城小程序', 'CRM系统升级', '数据分析平台', '移动APP开发',
    '智能仓储系统', '在线教育平台', '供应链管理', '物联网平台', '区块链应用'
  ]
  
  const assignees = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const priorities = ['low', 'medium', 'high']
  const priorityWeights = [0.2, 0.5, 0.3]
  const statuses = ['todo', 'doing', 'done']
  const statusWeights = [0.3, 0.4, 0.3]
  
  const tasks = []
  for (let i = 0; i < 45; i++) {
    // 根据权重选择优先级
    let priority = 'medium'
    let rand = Math.random()
    let cumWeight = 0
    for (let j = 0; j < priorities.length; j++) {
      cumWeight += priorityWeights[j]
      if (rand <= cumWeight) {
        priority = priorities[j]
        break
      }
    }
    
    // 根据权重选择状态
    let status = 'doing'
    rand = Math.random()
    cumWeight = 0
    for (let j = 0; j < statuses.length; j++) {
      cumWeight += statusWeights[j]
      if (rand <= cumWeight) {
        status = statuses[j]
        break
      }
    }
    
    const progress = status === 'done' ? 100 :
                    status === 'todo' ? 0 :
                    Math.floor(Math.random() * 90) + 10
    
    tasks.push({
      id: i + 1,
      title: taskTitles[i % taskTitles.length] + (i >= taskTitles.length ? ` ${Math.floor(i / taskTitles.length) + 1}` : ''),
      project: projects[Math.floor(Math.random() * projects.length)],
      assignee: assignees[Math.floor(Math.random() * assignees.length)],
      priority: priority,
      status: status,
      progress: progress,
      dueDate: `2025-${String(Math.floor(Math.random() * 3) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`
    })
  }
  
  return tasks
}

// 筛选后的任务
const filteredTasks = computed(() => {
  return allTasks.value.filter(task => {
    if (searchForm.title && !task.title.includes(searchForm.title)) {
      return false
    }
    if (searchForm.status && task.status !== searchForm.status) {
      return false
    }
    if (searchForm.priority && task.priority !== searchForm.priority) {
      return false
    }
    return true
  })
})

// 分页后的任务
const paginatedTasks = computed(() => {
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filteredTasks.value.slice(start, end)
})

const getPriorityType = (priority) => {
  const types = { low: 'info', medium: 'warning', high: 'danger' }
  return types[priority] || ''
}

const getPriorityLabel = (priority) => {
  const labels = { low: '低', medium: '中', high: '高' }
  return labels[priority] || priority
}

const getStatusType = (status) => {
  const types = { todo: 'info', doing: 'primary', done: 'success' }
  return types[status] || ''
}

const getStatusLabel = (status) => {
  const labels = { todo: '待办', doing: '进行中', done: '已完成' }
  return labels[status] || status
}

const getProgressColor = (progress) => {
  if (progress < 30) return '#f56c6c'
  if (progress < 70) return '#e6a23c'
  return '#67c23a'
}

const handleSearch = () => {
  loading.value = true
  pagination.page = 1 // 搜索时重置到第一页
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询成功')
  }, 300)
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.status = ''
  searchForm.priority = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
}

const handleCurrentChange = (page) => {
  pagination.page = page
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleAdd = () => {
  ElMessage.info('新建任务功能开发中...')
}

const handleEdit = (row) => {
  ElMessage.info(`编辑任务：${row.title}`)
}

const handleComplete = (row) => {
  const task = allTasks.value.find(t => t.id === row.id)
  if (task) {
    task.status = 'done'
    task.progress = 100
    ElMessage.success('任务已完成')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除任务"${row.title}"吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    const index = allTasks.value.findIndex(t => t.id === row.id)
    if (index > -1) {
      allTasks.value.splice(index, 1)
    }
    
    // 如果当前页没有数据，跳转到上一页
    const maxPage = Math.ceil(filteredTasks.value.length / pagination.size) || 1
    if (pagination.page > maxPage) {
      pagination.page = maxPage
    }
    
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 初始化数据
onMounted(() => {
  loading.value = true
  setTimeout(() => {
    allTasks.value = generateMockData()
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.tasks-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

